package com.example.levine.taobaolivecheck;

import android.accessibilityservice.AccessibilityService;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.provider.Settings;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.baichuan.android.trade.AlibcTrade;
import com.alibaba.baichuan.android.trade.callback.AlibcTradeCallback;
import com.alibaba.baichuan.android.trade.model.AlibcShowParams;
import com.alibaba.baichuan.android.trade.model.OpenType;
import com.alibaba.baichuan.android.trade.page.AlibcPage;
import com.alibaba.baichuan.trade.biz.context.AlibcTradeResult;
import com.alibaba.baichuan.trade.biz.core.taoke.AlibcTaokeParams;
import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;
import com.example.levine.taobaolivecheck.tools.L;
import com.example.levine.taobaolivecheck.tools.T;
import com.example.levine.taobaolivecheck.tools.TShow;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

import okhttp3.Call;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {

    private AlibcShowParams alibcShowParams;
    private HashMap exParams;
    public static final String LIVING = "LIVING";
    public static final String LIVED = "LIVED";
    public static final String FAIL = "FAIL";
    public static final String DEFAULT = "DEFAULT";
    public static final String DETECTION = "DETECTION";//检测中
    private Adapter adapter;
    private DownTimer downTimer;
    private TextView tv_start;
    private TextView tv_check;
    private int checkCount = 0;//当前检测的位置
    private int checkFailCount = 0;//检查失败次数
    private ListView listView;
    private MyHandler myHandler = new MyHandler();
    public static boolean isStop = false;
    private EntityLiveCheck entityLiveCheck;
    private int page = 1;
    private int nextTime = 10000;//步骤执行时间间隔

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initAlibc();
        listView = (ListView) findViewById(R.id.listview);
        tv_check = (TextView) findViewById(R.id.check);
        TextView tv_stop = (TextView) findViewById(R.id.stop);
        tv_start = (TextView) findViewById(R.id.tv_start);

        tv_check.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //开始检测
                if (!adapter.list.isEmpty()) {
                    check();
                } else {
                    TShow.showShort("暂无直播间");
                }

            }
        });
        tv_stop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //停止检测
                isStop = true;
            }
        });

        tv_start.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (serviceIsRunning()) {
                    TShow.showShort("服务已开启");
                } else {
                    startAccessibilityService();
                }
            }
        });

        MyListener myListener = new MyListener();
        MyService.setListener(myListener);

        adapter = new Adapter(new ArrayList<EntityLiveCheck.DataBean.RoomsBean>());
        listView.setAdapter(adapter);
        page = 1;
        getData(page);
    }

    private class MyHandler extends Handler {
        @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (isStop) {
                myHandler.removeCallbacksAndMessages(null);
                TShow.showShort("淘宝直播检测已停止");
                return;
            }
            switch (msg.what) {
                case 1:
                    checkCount++;
                    check();
                    break;
                case 2:
                    checkFailCount++;
                    check();
                    break;
                case 3:
                    if (serviceIsRunning()) {
                        check();
                    } else {
                        startAccessibilityService();
                    }
                    break;
                case 4:
                    Bundle bundle = msg.getData();
                    String status = bundle.getString("status");
                    String id = bundle.getString("id");
                    int count = bundle.getInt("count");
                    setLiveStatus(status, id, count);
                    break;
            }
        }
    }

    private class MyListener implements MyService.Listener {


        @Override
        public void success(String status) {
            EntityLiveCheck.DataBean.RoomsBean roomsBean = adapter.list.get(checkCount);
            switch (status) {
                case LIVED:
                    status = "0";
                    roomsBean.check_status = LIVED;
                    break;
                case LIVING:
                    status = "1";
                    roomsBean.check_status = LIVING;
                    break;
            }
            adapter.notifyDataSetChanged();
            setLiveStatus(status, roomsBean.getLive_id() + "", 0);
        }

        @Override
        public void fail() {
            EntityLiveCheck.DataBean.RoomsBean roomsBean = adapter.list.get(checkCount);
            roomsBean.check_status = FAIL;
            adapter.notifyDataSetChanged();
            myHandler.removeCallbacksAndMessages(null);
            if (checkFailCount >= 2) {
                setLiveStatus("0", roomsBean.getLive_id() + "", 0);
            } else {
                myHandler.sendEmptyMessageDelayed(2, nextTime);
            }
        }
    }

    /**
     * 设置直播状态
     */
    public void setLiveStatus(final String status, final String id, final int count) {
        String s = status.equals("1") ? "直播中" : "已停播";
        final android.support.v7.app.AlertDialog alertDialog =
                T.showDialog(getActivity(), "检测结果：" + s + "\n正在为该直播设置状态，请稍等...",
                        false).create();
        alertDialog.show();
        OkGo.post("https://ra.jade-box.com/live/" + id)
                .params("status", status + "")
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        alertDialog.dismiss();
                        EntityLiveCheck entityLiveCheck;
                        try {
                            entityLiveCheck = JSON.parseObject(s, EntityLiveCheck.class);
                        } catch (Exception e) {
                            onError(call, response, new Exception());
                            return;
                        }

                        if (entityLiveCheck.getCode() == 201) {
                            TShow.showShort(getActivity(), "提交成功");
                            adapter.list.get(checkCount).setStatus = "1";
                            adapter.notifyDataSetChanged();
                            myHandler.removeCallbacksAndMessages(null);
                            myHandler.sendEmptyMessageDelayed(1, nextTime);
                        } else {
                            TShow.showShort(getActivity(), "提交失败：" + entityLiveCheck.getCode());
                            adapter.list.get(checkCount).setStatus = "0";
                            adapter.notifyDataSetChanged();

                            if (count < 3) {
                                myHandler.removeCallbacksAndMessages(null);
                                Message message = new Message();
                                Bundle bundle = new Bundle();
                                bundle.putString("status", status + "");
                                bundle.putString("id", id + "");
                                int i = count;
                                i++;
                                bundle.putInt("count", i);
                                message.setData(bundle);
                                message.what = 4;
                                myHandler.sendMessageDelayed(message, nextTime);
                            } else {
                                myHandler.removeCallbacksAndMessages(null);
                                myHandler.sendEmptyMessageDelayed(1, nextTime);
                            }
                        }
                    }

                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        alertDialog.dismiss();
                        TShow.showShort(getActivity(), "提交失败");
                        adapter.list.get(checkCount).setStatus = "0";
                        adapter.notifyDataSetChanged();
                        if (count < 3) {
                            myHandler.removeCallbacksAndMessages(null);
                            Message message = new Message();
                            Bundle bundle = new Bundle();
                            bundle.putString("status", status + "");
                            bundle.putString("id", id + "");
                            int i = count;
                            i++;
                            bundle.putInt("count", i);
                            message.setData(bundle);
                            message.what = 4;
                            myHandler.sendMessageDelayed(message, nextTime);
                        } else {
                            myHandler.removeCallbacksAndMessages(null);
                            myHandler.sendEmptyMessageDelayed(1, nextTime);
                        }

                    }
                });
    }


    /**
     * 请求数据
     */
    public void getData(final int page) {
        OkGo.get("https://ra.jade-box.com/live?page=" + page + "&per_page=20&platform=taobao")
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        try {
                            entityLiveCheck = JSON.parseObject(s, EntityLiveCheck.class);
                        } catch (Exception e) {
                            onError(call, response, new Exception());
                            return;
                        }
                        if (entityLiveCheck.getCode() == 200) {
                            List<EntityLiveCheck.DataBean.RoomsBean> rooms = entityLiveCheck.getData().getRooms();
                            if (page == 1) {
                                checkCount = 0;
                                adapter.list.clear();
                            }
                            adapter.list.addAll(rooms);
                            adapter.notifyDataSetChanged();

                            TShow.showLong(getActivity(), "10秒后开始检测...");
                            myHandler.removeCallbacksAndMessages(null);
                            myHandler.sendEmptyMessageDelayed(3, 10000);
                        } else {
                            onError(call, response, new Exception());
                        }

                    }

                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        final android.support.v7.app.AlertDialog alertDialog =
                                T.showDialog(getActivity(), "请求失败，10秒后重试", false)
                                        .setPositiveButton("取消", new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                                downTimer.cancel();
                                            }
                                        }).create();
                        alertDialog.show();
                        downTimer = new DownTimer(alertDialog, 10000, "秒后重试");
                        downTimer.start();
                    }
                });
    }

    /**
     * 检测
     */
    private void check() {
        if (isStop) {
            myHandler.removeCallbacksAndMessages(null);
            TShow.showShort("淘宝直播检测已停止");
            return;
        }
        if (checkCount == adapter.list.size()) {
            if (entityLiveCheck.getData().isHas_next()) {
                //获取下一页的数据
                page++;
                getData(page);
            } else {
                final android.support.v7.app.AlertDialog alertDialog =
                        T.showDialog(getActivity(), "120秒后重新检测", false)
                                .setPositiveButton("取消", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        downTimer.cancel();
                                    }
                                }).create();
                alertDialog.show();
                downTimer = new DownTimer(alertDialog, 120000, "秒后重新检测");
                downTimer.start();
            }
            return;
        }
        EntityLiveCheck.DataBean.RoomsBean roomsBean = adapter.list.get(checkCount);
        roomsBean.check_status = DETECTION;
        adapter.notifyDataSetChanged();
        listView.smoothScrollToPosition(checkCount);
        openTaobao(roomsBean.getCheck_basis() + "");
    }


    private class DownTimer extends CountDownTimer {
        private android.support.v7.app.AlertDialog alertDialog;
        private String s;

        public DownTimer(android.support.v7.app.AlertDialog alertDialog, int i, String s) {
            super(i, 1000);
            this.alertDialog = alertDialog;
            this.s = s;
        }

        @Override
        public void onTick(long millisUntilFinished) {
            alertDialog.setMessage(millisUntilFinished / 1000 + s);
        }

        @Override
        public void onFinish() {
            alertDialog.dismiss();
            if (entityLiveCheck.getData().isHas_next()) {
                //获取下一页的数据
                page++;
                getData(page);
            } else {
                page = 1;
                getData(page);
            }
        }
    }

    public MainActivity getActivity() {
        return this;
    }

    private class Adapter extends BaseAdapter {
        public List<EntityLiveCheck.DataBean.RoomsBean> list;

        public Adapter(List<EntityLiveCheck.DataBean.RoomsBean> list) {
            this.list = list;
        }

        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public Object getItem(int position) {
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            Holder holder;
            if (convertView == null) {
                holder = new Holder();
                convertView = getLayoutInflater().inflate(R.layout.item, null);
                holder.tv = (TextView) convertView.findViewById(R.id.tv);
                holder.status = (TextView) convertView.findViewById(R.id.status);
                holder.set_status = (TextView) convertView.findViewById(R.id.set_status);
                holder.iv = (ImageView) convertView.findViewById(R.id.iv);
                convertView.setTag(holder);
            } else {
                holder = (Holder) convertView.getTag();
            }
            EntityLiveCheck.DataBean.RoomsBean roomsBean = adapter.list.get(position);
            holder.tv.setText(roomsBean.getTitle() + "");
            Glide.with(getActivity()).load(roomsBean.getCover()).crossFade().into(holder.iv);
            switch (roomsBean.setStatus) {
                case "1":
                    holder.set_status.setText("提交成功");
                    holder.set_status.setBackgroundColor(Color.BLACK);
                    break;
                case "0":
                    holder.set_status.setText("提交失败");
                    holder.set_status.setBackgroundColor(Color.BLACK);
                    break;
                case DEFAULT:
                    holder.set_status.setText("等待检测");
                    holder.set_status.setBackgroundColor(Color.BLACK);
                    break;
            }
            switch (roomsBean.check_status) {
                case LIVING:
                    holder.status.setText("检测状态：直播中");
                    holder.status.setBackgroundColor(Color.GREEN);
                    holder.status.setBackgroundResource(R.color.d_green);
                    break;
                case LIVED:
                    holder.status.setText("检测状态：已停播");
                    holder.status.setBackgroundResource(R.color.d_blue);
                    break;
                case FAIL:
                    holder.status.setBackgroundResource(R.color.d_red);
                    holder.status.setText("检测状态：检测失败");
                    break;
                case DEFAULT:
                    holder.status.setText("检测状态：未检测");
                    holder.status.setBackgroundResource(R.color.d_gray);
                    break;
                case DETECTION:
                    holder.status.setText("检测中...");
                    holder.status.setBackgroundResource(R.color.d_ye);
                    break;
            }

            return convertView;
        }

        private class Holder {
            public TextView tv;
            public TextView status;
            public TextView set_status;
            public ImageView iv;
        }
    }

    /**
     * 前往设置界面开启服务
     */
    private void startAccessibilityService() {
        new AlertDialog.Builder(this)
                .setTitle("开启辅助功能")
                .setIcon(R.mipmap.ic_launcher)
                .setMessage("使用此项功能需要您开启辅助功能")
                .setPositiveButton("立即开启", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // 隐式调用系统设置界面
                        Intent intent = new Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS);
                        startActivity(intent);
                    }
                }).create().show();
    }

    /**
     * 判断自己的应用的AccessibilityService是否在运行
     *
     * @return
     */
    private boolean serviceIsRunning() {
        ActivityManager am = (ActivityManager) getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningServiceInfo> services = am.getRunningServices(Short.MAX_VALUE);
        for (ActivityManager.RunningServiceInfo info : services) {
            if (info.service.getClassName().equals(getPackageName() + ".MyService")) {
                return true;
            }
        }
        return false;
    }

    private void initAlibc() {
        alibcShowParams = new AlibcShowParams(OpenType.Auto, false);
        exParams = new HashMap<>();
        exParams.put("isv_code", "appisvcode");
        exParams.put("alibaba", "阿里巴巴");//自定义参数部分，可任意增删改
        alibcShowParams = new AlibcShowParams(OpenType.Native, false);
        alibcShowParams.setClientType("taobao_scheme");
    }

    private void openTaobao(String url) {
        AlibcTaokeParams alibcTaokeParams = new AlibcTaokeParams();
        alibcTaokeParams.adzoneid = "57328044";
        alibcTaokeParams.pid = "mm_26632322_6858406_23810104";
        alibcTaokeParams.subPid = "mm_26632322_6858406_23810104";
        alibcTaokeParams.extraParams = new HashMap<>();
        alibcTaokeParams.extraParams.put("taokeAppkey", "24907828");

        AlibcTrade.show(this, new AlibcPage(url),
                alibcShowParams,
                alibcTaokeParams,
                exParams,
                new AlibcTradeCallback() {
                    @Override
                    public void onTradeSuccess(AlibcTradeResult alibcTradeResult) {

                    }

                    @Override
                    public void onFailure(int i, String s) {

                    }
                });
    }
}
